const { dialog ,net,Notification,BrowserWindow} = require('electron');
const path = require('path');
const fs = require('fs');
// 选择文件夹并且保存文件
function Save(ObjURL,format = 'jpg',parent = undefined){
    const Path = `C:/Users/Administrator/Pictures/${Math.random().toString(36).slice(2)}.${format}`;
    dialog.showSaveDialog(parent,{
        title:'保存文件',
        buttonLabel:'保存',
        defaultPath:Path,
        filters:[
            { name: 'Images', extensions: ['jpg', 'png', 'gif'] },
            { name: 'All Files', extensions: ['*'] }
        ]
    }).then(suc=>{
        if(!suc.canceled){
            const request = net.request(ObjURL);
            request.on('response',(response)=>{
                let buf = Buffer.alloc(0);
                response.on('data',(chunk)=>{
                    buf = Buffer.concat([buf,chunk],buf.length+chunk.length);
                });
                response.on('end',()=>{
                    fs.writeFileSync(suc.filePath,buf,'utf8');
                    new Notification({
                        'title':'保存图片成功',
                        'body':'图片成功保存到'+suc.filePath
                    }).show();
                });
            });
            request.end();
        }
    });
}
//窗口创建函数
const createWin = function(titleBarStyle = 'default'){
    return new BrowserWindow({
        minWidth:800,
        minHeight:600,
        width:1000,
        height:600,
        icon:'',
        titleBarStyle:titleBarStyle,
        webPreferences:{
            preload: path.join(__dirname, 'preload.js'),
            webSecurity:false
        }
    })
}
module.exports = {Save,createWin};